import {Form, Input, Select, Button, TreeSelect, message} from 'antd';
import React from 'react';
import qs from 'qs';
import * as Request from "../../Server/SystemManger";
import * as Const from "../../common/const";

require('./customer.css');

const FormItem = Form.Item;
const {Option} = Select;
const TreeNode = TreeSelect.TreeNode;

class ResourceForms extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            parentid: this.props.permission && this.props.permission.parentid + ''
        };
    }

    componentWillMount() {
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                values.type = Number(values.type);
                values.parentId ? (values.parentId = 0) : null;//不选择默认给根节点
                values.parentId = Number(values.parentId);
                values.name = values.name.replace(/\s*/g,"");
                values.permission = values.permission.replace(/\s*/g,"");
                Request.editOrSavePermission(qs.stringify(values)).then(res => {
                    if (res && Const.REQUEST_SUCCESS == res.code) {
                        message.success(Const.OPERATION_SUCCESS_TIP, Const.AUTO_DISAPPEAR_TIME);
                        this.props.cancel(true);
                    }
                });
            }
        });
    }
    renderTreeNodes = (data) => {
        data = data.filter(item => item.type == 1);
        return data.map((item) => {
            if (item.type == 2) return;
            if (item.children && item.children.length) {
                return (
                    <TreeNode title={item.title} value={item.id + ''} key={item.id + ''}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            delete item.children;
            return <TreeNode title={item.title} value={item.id + ''} key={item.id + ''}/>;
        });
    }
    onChange = (value) => {
        this.props.form.setFieldsValue({parentid: value + ''});
    }
    validatorPermission = (rule, value, callback) => {
        if (!value || !value.length) {
            callback();return;
        }
        const id = this.props.form.getFieldValue('id');
        let params = {permission: value};
        id && (params.id = id);
        Request.validatorPermission(qs.stringify(params)).then(res => {
            if (res && Const.REQUEST_SUCCESS == res.code && !res.data) {
                callback(Const.VALIDATOR_FAIL_TIP);
            } else {
                callback();//注意:回调函数必须调用
            }
        });
    }
    validatorName = (rule, value, callback) => {
        if (!value || !value.length) {
            callback();
            return;
        }
        if (value.replace(/ /g, '').length !== value.length) {
            callback('资源名称不能含有空格!');
        } else {
            callback();
        }
    }

    render() {
        const {getFieldDecorator} = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 5},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 19},
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        };

        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem>
                    {getFieldDecorator('id', {
                        initialValue: this.props.permission && this.props.permission.id,
                    })(
                        <Input type={'hidden'}/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="父资源"
                >
                    {getFieldDecorator('parentid', {
                        initialValue: this.state.parentid
                    })(
                        <TreeSelect
                            onChange={this.onChange}
                        >
                            {this.renderTreeNodes([{title: '无父资源', id: 0, type: 1}, ...this.props.treeData])}
                        </TreeSelect>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="资源类型"
                >
                    {getFieldDecorator('type', {
                        rules: [{
                            required: true, message: '请选择资源类型!',
                        }],
                        initialValue: this.props.permission && this.props.permission.type + '',
                    })(
                        <Select>
                            <Option value='1'>菜单</Option>
                            <Option value='2'>按钮</Option>
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="资源名称"
                >
                    {getFieldDecorator('name', {
                        rules: [{
                            required: true, message: '请输入资源名称!',
                        }, {
                            validator: this.validatorName
                        }],
                        initialValue: this.props.permission && this.props.permission.name,
                    })(
                        <Input maxLength={255}/>
                    )}
                </FormItem>
                {/*<FormItem
                    {...formItemLayout}
                    label={'链接'}
                >
                    {getFieldDecorator('href', {
                        rules: [{required: true, message: 'Please input your nickname!', whitespace: true}],
                    })(
                        <Input/>
                    )}
                </FormItem>*/}
                <FormItem
                    {...formItemLayout}
                    label={'权限标识'}
                >
                    {getFieldDecorator('permission', {
                        rules: [
                            {required: true, message: '请输入权限标识！'}
                            , {
                                validator: this.validatorPermission,
                            }],
                        initialValue: this.props.permission && this.props.permission.permission,
                    })(
                        <Input maxLength={255}/>
                    )}
                </FormItem>
                {/*<FormItem
                    {...formItemLayout}
                    label="访问路径"
                >
                    {getFieldDecorator('urlpattern', {
                        initialValue: this.props.permission && this.props.permission.urlpattern,
                    })(
                        <Input maxLength={255}/>
                    )}
                </FormItem>*/}
                {/*<FormItem
                    {...formItemLayout}
                    label="权重"
                >
                    {getFieldDecorator('weight', {
                        rules: [{ required: true, message: 'Please input website!' }],
                    })(
                        <Input/>
                    )}
                </FormItem>*/}
                {<FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">保存</Button>
                    <Button type="primary" onClick={this.props.cancel}>返回</Button>
                </FormItem>}
            </Form>
        );
    }
}

const WrappedResourceForms = Form.create()(ResourceForms);

export default WrappedResourceForms;